import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { LoginAuthDtoToUserName } from './dto/login-auth.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { JwtService } from '@nestjs/jwt';
import { CreateAuthDto } from './dto/create-auth.dto';
import { md5 } from 'src/utils/md5';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class AuthService {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly jwtService: JwtService,
    private readonly redisService: RedisService,
  ) {}
  async login(loginAuthDtoToUserName: LoginAuthDtoToUserName) {
    try {
      const res = await this.prismaService.user.findUnique({
        where: {
          username: loginAuthDtoToUserName.username,
          password: md5(loginAuthDtoToUserName.password),
        },
        include: {
          UserToRole: {
            select: {
              roleId: true,
            },
          },
        },
      });

      console.log(res, 'res----user');

      if (!res) {
        throw new HttpException('账号或密码错误', HttpStatus.BAD_REQUEST);
      }

      return {
        token: this.jwtService.sign({
          username: res.username,
          id: res.id,
          roles: res.UserToRole.map((item) => item.roleId),
        }),
      };
    } catch (error) {
      throw new HttpException(error.response, error.status);
    }
  }

  async register(registerDto: CreateAuthDto) {
    try {
      const user = await this.prismaService.user.findUnique({
        where: {
          username: registerDto.username,
        },
      });
      if (user) {
        throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST);
      }

      if (registerDto.password !== registerDto.confirmPassword) {
        throw new HttpException('两次密码不一致', HttpStatus.BAD_REQUEST);
      }

      const code = await this.redisService.get(registerDto.email);

      if (!code) {
        throw new HttpException('验证码已过期', HttpStatus.BAD_REQUEST);
      }

      if (code != registerDto.code) {
        throw new HttpException('验证码错误', HttpStatus.BAD_REQUEST);
      }

      await this.prismaService.user.create({
        data: {
          username: registerDto.username,
          password: md5(registerDto.password),
          email: registerDto.email,
          UserToRole: {
            create: {
              roleId: 2,
            },
          },
        },
      });

      return {
        code: 200,
        msg: '注册成功',
      };
    } catch (error) {
      console.log(error, 'error');
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }
}
